import React, { useState, useCallback, useEffect } from 'react';
import { Layout, message, Spin } from 'antd';
import ImageUploader from '../components/converter/ImageUploader';
import StyleSelector from '../components/converter/StyleSelector';
import TextPrompt from '../components/converter/TextPrompt';
import ImageResult from '../components/converter/ImageResult';
import Header from '../components/layout/Header';
import { generateStyledImage } from '../services/aiService';

const { Content } = Layout;

const ProductPage = () => {
  const [uploadedImage, setUploadedImage] = useState(null);
  const [selectedStyle, setSelectedStyle] = useState('none');
  const [textPrompt, setTextPrompt] = useState('');
  const [resultImage, setResultImage] = useState(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [generationProgress, setGenerationProgress] = useState(0);
  const [error, setError] = useState(null);
  const [appReady, setAppReady] = useState(false);

  // 应用加载动画
  useEffect(() => {
    const timer = setTimeout(() => {
      setAppReady(true);
    }, 500);
    return () => clearTimeout(timer);
  }, []);

  // 创建全局消息通知样式
  useEffect(() => {
    message.config({
      top: 80,
      duration: 3,
      maxCount: 3,
    });
  }, []);

  // 优化：根据风格选择自动提供文本建议
  useEffect(() => {
    if (selectedStyle !== 'none' && selectedStyle !== 'custom') {
      const styleSuggestions = {
        miyazaki: `转换为受吉卜力工作室视觉美学启发的动漫风格插图。保留原始构图和关键元素，但使用吉卜力风格的特征重新构想它们。力求营造一种异想天开的怀旧氛围，捕捉吉卜力电影中经常出现的魔幻现实主义，例如《龙猫》、《千与千寻》或《哈尔的移动城堡》`,
        lego: '乐高积木风格，色彩鲜明，块状结构清晰',
        pixar: '皮克斯3D动画风格，光滑细腻的渲染效果',
        disney: '迪士尼动画风格，充满童话感和快乐氛围',
      };
      
      setTextPrompt(styleSuggestions[selectedStyle] || '');
    }
  }, [selectedStyle]);

  // 模拟进度条更新
  const simulateProgress = useCallback(() => {
    const calculateNextProgress = (current) => {
      if (current >= 95) return 95;
      
      // 在不同阶段使用不同的增长速度
      if (current < 30) return Math.floor(current + Math.random() * 5 + 3);
      if (current < 60) return Math.floor(current + Math.random() * 3 + 2);
      if (current < 85) return Math.floor(current + Math.random() * 2 + 1);
      return Math.floor(current + Math.random() * 1 + 0.5);
    };

    const interval = setInterval(() => {
      setGenerationProgress(prev => {
        const next = calculateNextProgress(prev);
        return Math.min(95, next);
      });
    }, 300);

    return interval;
  }, []);

  // 图像生成函数
  const generateImage = useCallback(async () => {
    // 验证输入
    if (!uploadedImage) {
      message.error('请先上传图片');
      return;
    }

    if (selectedStyle === 'custom' && !textPrompt.trim()) {
      message.warning('使用自定义风格时，请提供文字描述');
      return;
    }

    setError(null);
    setIsGenerating(true);
    setGenerationProgress(0);

    // 启动进度条动画
    const progressInterval = simulateProgress();

    try {
      // 调用AI服务生成图像
      const generatedImageUrl = await generateStyledImage(
        uploadedImage,
        textPrompt,
        selectedStyle
      );
      
      // 设置进度为100%
      clearInterval(progressInterval);
      setGenerationProgress(100);
      
      // 设置结果图像
      setResultImage(generatedImageUrl);
      
      message.success({
        content: '图像生成成功！',
        icon: <span role="img" aria-label="success">✨</span>
      });
    } catch (err) {
      clearInterval(progressInterval);
      setError(err.message || '图像生成失败，请重试');
      message.error({
        content: err.message || '图像生成失败，请重试',
        icon: <span role="img" aria-label="error">❌</span>
      });
    } finally {
      setIsGenerating(false);
    }
  }, [uploadedImage, selectedStyle, textPrompt, simulateProgress]);

  // 处理重置功能
  const handleReset = useCallback(() => {
    setUploadedImage(null);
    setSelectedStyle('none');
    setTextPrompt('');
    setResultImage(null);
    setError(null);
    message.info('已重置所有设置');
  }, []);

  if (!appReady) {
    return (
      <div className="app-loading">
        <Spin size="large" />
        <p>加载中...</p>
      </div>
    );
  }

  return (
    <Layout className="app-layout">
      <Header onReset={handleReset} />
      
      <Content className="app-content">
        <div className="main-container">
          <div className="left-panel">
            <ImageUploader 
              onImageUpload={setUploadedImage} 
              disabled={isGenerating}
              currentImage={uploadedImage}
            />
          </div>
          
          <div className="right-panel">
            <StyleSelector 
              selectedStyle={selectedStyle} 
              onStyleSelect={setSelectedStyle}
              disabled={isGenerating || !uploadedImage}
            />
            
            <TextPrompt 
              value={textPrompt} 
              onChange={setTextPrompt} 
              onGenerate={generateImage}
              isGenerating={isGenerating}
              disabled={!uploadedImage || isGenerating}
            />
            
            <ImageResult 
              resultImage={resultImage} 
              isGenerating={isGenerating}
              progress={generationProgress}
              error={error}
              onRetry={generateImage}
            />
          </div>
        </div>
      </Content>
    </Layout>
  );
};

export default ProductPage; 